/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { BaseCommand, CMEVENTS, pickedFaceData } from '@amcax/base';
import { Picker3D, PickerMgr } from '@amcax/renderer';
import { eventCenterManager } from '@app-base/common/events/EventCenterManager';
import {
  NumberInputFormat,
  PickInputRJSFFormat,
} from '@app-cad/common/components/command-form/constants';
import { PickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { previewer, userEvents } from '@app-cad/module';
import { wsApi } from '@app-cad/server';
import { FeaturedCmdDialogParams } from '@app-cad/types';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import i18n from 'i18next';
import { useEffect, useMemo, useState } from 'react';

type FormData = {
  faces?: Array<pickedFaceData>;
  offset?: number;
};

// 抽壳
function ShellDialog({ title, onClose, props }: FeaturedCmdDialogParams) {
  const { picker } = useTools();
  const [formData, setFormData] = useState<FormData>({
    faces: [],
    offset: 1,
  });
  useEffect(() => {
    eventCenterManager.activeEventCenter.setState('array').addExit(exit);
    // 注册原始模型删除事件
    userEvents.on(CMEVENTS.MODEL_ADDED, newModelAdded);
    return () => {
      exit();
    };
  }, []);
  const getParams = () => {
    const ids = formData.faces.map((data) => data.idInfo.i);
    return {
      base: formData.faces[0].idInfo.o,
      faces: ids,
      offset: formData.offset,
    };
  };
  useAsyncEffect(async () => {
    // const _isSameShell = formData.face && isSameShell([formData.face]);
    // if (!_isSameShell) {
    //   MessageTip.error('选择的面必须在同一个体上');
    // }

    if (formValidate()) {
      let result;
      if (props == null) {
        result = await wsApi.createShell(getParams(), true);
      } else {
        result = await wsApi.setParams(props.shape, getParams(), true);
      }
      previewInCommand(result);
    } else {
      previewer.clear();
    }
  }, [formData]);
  const formValidate = () => {
    if (formData.faces.length > 0 && formData.offset) {
      return true;
    } else {
      return false;
    }
  };
  const finishValid = useMemo(formValidate, [formData]);
  useAsyncEffect(async () => {
    if (props == null) {
      return;
    }
    const { faces, offset } = props.params;
    for (const i of faces) {
      await initEditDependency([`${props.baseid}:f${i}`]);
    }
    const planeObj =
      faces?.length > 0 &&
      faces.map((i) => {
        return picker.generatePickObjByPickID(
          `${props.baseid}:f${i}`,
        ) as pickedFaceData;
      });

    setFormData({
      faces: planeObj,
      offset,
    });
  }, []);
  const newModelAdded = () => {
    onClose();
    // Picker.deleteModels([interactonData.current.pickedObject.idInfo.o], true)
  };

  // 判断选择的面是否在同一个体上
  // const isSameShell = (planes: any[]) => {
  //   const shellSet = new Set();
  //   for (let i = 0; i < planes.length; i++) {
  //     const modelDxid = planes[i].idInfo.o;
  //     shellSet.add(modelDxid);
  //   }
  //   return shellSet.size === 1;
  // };

  const handleExecute = async () => {
    if (formData.faces.length > 0 && formData.offset) {
      if (props == null) {
        await wsApi.createShell(getParams());
      } else {
        await wsApi.setParams(props.shape, getParams());
      }
      previewer.clear();
    }
    onClose();
  };

  const exit = () => {
    eventCenterManager.activeEventCenter.setDefault();
    userEvents.off(CMEVENTS.MODEL_ADDED, newModelAdded);
    PickerMgr.getPicker<Picker3D>('3d').init();
  };
  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      faces: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        uniqueItems: true,
        title: '抽壳面',
        format: PickInputRJSFFormat.MultiPickFace,
      },
      offset: {
        type: 'number',
        title: '厚度',
        minimum: 0.000001,
        format: NumberInputFormat.Length,
      },
    },
  };
  const checkAndFinishDraw = async () => {
    handleExecute();
    onClose();
  };
  const { initEditDependency, initingEdit, previewInCommand } = useCommand(
    'cmd-shell',
    {
      onClose,
      finishDraw: checkAndFinishDraw,
    },
  );
  return (
    <PickableCommandForm
      isFormDataValid={finishValid}
      disabled={initingEdit}
      onClose={onClose}
      title={title}
      schema={schema}
      formData={formData}
      onChange={setFormData}
      extraUiSchema={{
        faces: {
          'ui:placeholder': '请输入平面',
          'ui:autofocus': true,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}

export const cmdShell: BaseCommand = {
  id: 'cmdShell',
  label: 'command.shell',
  icon: 'commands/feature/shell',
  create: (label: string, onClose: () => void, props) => (
    <ShellDialog
      title={i18n.t(label)}
      onClose={onClose}
      props={props}
      placement='topLeft'
    />
  ),
};
